/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.tasks.text;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.Collections;
import java.util.Set;

import taskgraph.ports.CharInputPort;
import taskgraph.ports.CharOutputPort;
import taskgraph.tasks.PrimitiveTask;


/**
 * Reports distinct, unique or repeated lines, with or without counts.
 * <p>The default command is to filter distinct lines, with a single entry 
 * when there are duplicate, consecutive lines.
 * 
 * @author Armando Blancas
 * @see taskgraph.ports.CharInputPort
 * @see taskgraph.ports.CharOutputPort
 */
public class UniqueLines extends PrimitiveTask {
	
	public enum UNIQ_F { UNIQUE, REPEATED, COUNT, IGNORE_CASE };

	private CharInputPort input;
	private CharOutputPort output;
	private Set<UNIQ_F> flags = Collections.emptySet();
	
	/**
	 * This constructor allows creating instances as beans.
	 */
    public UniqueLines() {
    	// do nothing
    }

	/**
     * Creates an instance for selecting distinct lines.
     * 
     * @param input The char input port.
     * @param output The char output port.
     */
    public UniqueLines(final CharInputPort input, 
    		           final CharOutputPort output) {
    	setInput(input);
    	setOutput(output);
    }

	/**
     * Creates a fully configured instance.
     * 
     * @param input The char input port.
     * @param output The char output port.
     * @param flags The set of choices.
     */
    public UniqueLines(final CharInputPort input, 
    		           final CharOutputPort output, 
    		           final Set<UNIQ_F> flags) {
    	setInput(input);
    	setOutput(output);
    	setFlags(flags);
    }

    /**
	 * Gets the set of command options.
	 * 
	 * @return The set of flags.
	 */
	public Set<UNIQ_F> getFlags() {
		return flags;
	}
	
    /**
     * Gets the input port.
     * 
	 * @return The char input port.
	 */
	public CharInputPort getInput() {
		return input;
	}
	
	/**
     * Gets the output port.
     * 
	 * @return The char output port.
	 */
	public CharOutputPort getOutput() {
		return output;
	}
	
	/**
     * Reads lines from the input port and writes repeated or non-repeated 
     * lines, with or without counts, as requested.
	 *<pre>
	 *while not EOF
	 *    read a line from input port
	 *    report line as requested
	 *close input port
	 *close output port
	 *</pre>
	 */
	@Override
    public void run() {
    	try {
    		boolean keepCount  = flags.contains(UNIQ_F.COUNT);
    		boolean unique     = flags.contains(UNIQ_F.UNIQUE);
    		boolean repeated   = flags.contains(UNIQ_F.REPEATED);
    		boolean countAll   = !(unique ||repeated);
    		boolean ignoreCase = flags.contains(UNIQ_F.IGNORE_CASE); 
    		
    		String last = input.readLine();
    		if (last == null) {
    			return;
    		}
    		
    		int count = 1;    		
    		while (!Thread.currentThread().isInterrupted()) {
    			String line = input.readLine();
    			
    			Boolean duplicate = false;
    			if (line != null) {
    				duplicate = ignoreCase ? line.equalsIgnoreCase(last) : 
    					                     line.equals(last);
    			}
    			
    			if (duplicate) {
    				count++;
    			} else {
    				boolean printIt = countAll;
    				if (unique) {
    					printIt = (count == 1);
    				}
    				else if (repeated) {
    					printIt = (count > 1);
    				}
    				if (printIt) {
    					if (keepCount) { 
    						output.printf("%6d ", count);
    					}
    					output.println(last);
    				}

    				if (line == null) {
    					break;
    				}
    				
    				count = 1;
       				last = line;
    			}
            } 
        } catch (InterruptedIOException ie) {
        	// interruption request
        } catch (IOException ioe) {
        	// pipe synch error
            log.error("UniqeLines#run()", ioe);
        } finally {
			input.close();
			output.close();
        }
    }
	
	/**
	 * Sets the commands options for counting.
	 * 
	 * @param flags The set of flags.
	 */
	public void setFlags(final Set<UNIQ_F> flags) {
    	if (flags == null)
    		throw new IllegalArgumentException("flags == null");
    	if (flags.contains(UNIQ_F.UNIQUE) && flags.contains(UNIQ_F.REPEATED))
    		throw new IllegalArgumentException("cannot do unique and repeated");    	
		this.flags = flags;
	}

	/**
	 * Sets the input port.
	 * 
	 * @param input The char input port.
	 */
    public void setInput(final CharInputPort input) {
    	if (input == null)
    		throw new IllegalArgumentException("input == null");
 		this.input = input;
	}

	/**
	 * Sets the output port.
	 * 
	 * @param output The char output port.
	 */
    public void setOutput(final CharOutputPort output) {
    	if (output == null)
    		throw new IllegalArgumentException("output == null");
 		this.output = output;
	}

}
